package com.shallowUniverse.process.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shallowUniverse.process.entity.ProcessDefinition;
import com.shallowUniverse.process.exception.ProcessNotCompletedException;
import com.shallowUniverse.process.mapper.ApprovalMapper;
import com.shallowUniverse.process.mapper.ProcessDefinitionMapper;
import com.shallowUniverse.process.mapper.ProcessNodeDefinitionMapper;
import com.shallowUniverse.process.service.ProcessDefinitionService;
import com.shallowUniverse.process.utils.AssertUtil;
import com.shallowUniverse.process.utils.ProcessUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author gs
 * @date create in 2020/12/11 17:05
 */
@AllArgsConstructor
public class ProcessDefinitionServiceImpl implements ProcessDefinitionService {

    private final ProcessDefinitionMapper processDefinitionMapper;
    private final ProcessNodeDefinitionMapper processNodeDefinitionMapper;
    private final ApprovalMapper approvalMapper;

    @Override
    public List<ProcessDefinition> find(ProcessDefinition processDefinition) {
        return processDefinitionMapper.selectList(processDefinition);
    }

    @Override
    public ProcessDefinition findById(Long id) {
        return processDefinitionMapper.selecyById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(ProcessDefinition processDefinition) {
        if (ObjectUtils.isEmpty(processDefinition)) {
            return 0;
        }
        if (ObjectUtils.isEmpty(processDefinition.getCreateDate())) {
            processDefinition.setCreateDate(DateUtil.now());
        }
        return processDefinitionMapper.insert(processDefinition);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int remove(List<Long> ids, boolean isLogic) throws ProcessNotCompletedException {
        //判斷是否传递了id
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        //转换id
        String idsStr = ProcessUtil.parseCollectionToString(ids);
        //校验是否还存在未完成的流程
        AssertUtil.processNotCompleted(approvalMapper.selectNotCompletedByProcess(idsStr));
        //判断是做逻辑删除还是直接删除
        if (isLogic) {
            return processNodeDefinitionMapper.deleteByProcessLogic(idsStr) + processDefinitionMapper.deleteLogic(idsStr);
        } else {
            return processNodeDefinitionMapper.deleteByProcess(idsStr) + processDefinitionMapper.delete(idsStr);
        }
    }

    @Override
    public IPage<ProcessDefinition> findPage(IPage<ProcessDefinition> page, ProcessDefinition processDefinition) {
        //返回
        return processDefinitionMapper.selectPage(page,processDefinition);
    }
}
